package concurrent.deadlock;

import java.util.Date;

/**
 * @author why
 * @data 2021/8/31
 */
public class LockTest {
    public static String obj1 = "obj1";
    public static String obj2 = "obj2";

    public static void main(String[] args) {
        LockA lockA = new LockA();
        LockB lockB = new LockB();
        new Thread(lockA).start();
        new Thread(lockB).start();
    }
}

class LockA implements Runnable {

    @Override
    public void run() {
        while (true) {
            synchronized (LockTest.obj1) {
                System.out.println(new Date().toString() + " LockA 锁住 obj1");
                try {
                    Thread.sleep(3000); // 此处等待是给B能锁住机会
                    synchronized (LockTest.obj2) {
                        System.out.println(new Date().toString() + " LockA 锁住 obj2");
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

class LockB implements Runnable {

    @Override
    public void run() {
        while (true) {
            synchronized (LockTest.obj2) {
                System.out.println(new Date().toString() + " LockB 锁住 obj2");
                try {
                    Thread.sleep(3000); // 此处等待是给B能锁住机会
                    synchronized (LockTest.obj1) {
                        System.out.println(new Date().toString() + " LockB 锁住 obj1");
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
